﻿using Itech_Run.Sys.HttpApi.Controllers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Itech_Run.Sys.HttpApi.Middleware
{
    public class AutoAuthMiddleware
    {
        private readonly IConfiguration _configuration;
        /// <summary>
        /// 委托
        /// </summary>
        private readonly RequestDelegate _next;

        public AutoAuthMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        public async Task Invoke(HttpContext context)
        {
#if DEBUG
            string? userId = _configuration.GetSection("AutoLogin:UserId").Value;
            if (!context.Request.Headers.ContainsKey("Authorization") && !string.IsNullOrEmpty(userId))
            {
                //Bearer Scheme(JwtBearerDefaults):The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler'
                var token = context.RequestServices.GetRequiredService<AuthController>().getJwtToken(new Claim[] { new Claim(ClaimTypes.Name, userId) });
                context.Request.Headers.Add("Authorization", "Bearer " + token);
            }
#endif
            await _next(context);
        }
    }
}
